#!/usr/bin/env sh

echo Running pre-commit hook

# Check for required binaries, otherwise don't run
if ! command -v grep &> /dev/null
then
    echo "grep could not be found - skipping pre-commit"
    exit 0
fi

if ! command -v sed &> /dev/null
then
    echo "sed could not be found - skipping pre-commit"
    exit 0
fi

if ! command -v xargs &> /dev/null
then
    echo "xargs could not be found - skipping pre-commit"
    exit 0
fi

# Run pre-commit, this checks if we changed any golang files and runs the checks.
# The files are then git-added
FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep .go | sed 's| |\\ |g')
if [ -n "$FILES" ]; then
    make format
    make lint
    if [ $? -ne 0 ]; then
            echo "Error running make check - please fix before committing"
        echo "if this is a mistake you can skip the checks with 'git commit --no-verify'"
        exit 1
    fi
    echo "$FILES" | xargs git add
fi

exit 0
